package ciicos.check.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.check.entity.CheckTaskAnomalyEntity;
import ciicos.check.entity.CheckTaskEntity;
import ciicos.check.mapper.CheckTaskAnomalyMapper;
import ciicos.check.model.checktaskanomaly.CheckTaskAnomalyForm;
import ciicos.check.model.checktaskanomaly.CheckTaskAnomalyPagination;
import ciicos.check.service.CheckTaskAnomalyService;
import ciicos.check.service.CheckTaskService;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.ServletUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 巡检异常
 * 版本： V3.2.0
 * 版权：
 * 作者： 产研项目租
 * 日期： 2023-08-01
 */
@Service
public class CheckTaskAnomalyServiceImpl extends ServiceImpl<CheckTaskAnomalyMapper, CheckTaskAnomalyEntity> implements CheckTaskAnomalyService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;

    @Autowired
    private CheckTaskService checkTaskService;


    @Override
    public List<CheckTaskAnomalyEntity> getList(CheckTaskAnomalyPagination checkTaskAnomalyPagination) {
        return getTypeList(checkTaskAnomalyPagination, checkTaskAnomalyPagination.getDataType());
    }

    @Override
    public List<CheckTaskAnomalyEntity> getTypeList(CheckTaskAnomalyPagination checkTaskAnomalyPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int checkTaskAnomalyNum = 0;
        QueryWrapper<CheckTaskAnomalyEntity> checkTaskAnomalyQueryWrapper = new QueryWrapper<>();

//树形，异步父级查询条件
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(checkTaskAnomalyPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(checkTaskAnomalyPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();


            int checkTaskAnomalyNum1 = 0;
            QueryWrapper<CheckTaskAnomalyEntity> checkTaskAnomalySuperWrapper = new QueryWrapper<>();
            checkTaskAnomalyNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(checkTaskAnomalySuperWrapper, superQueryList, matchLogic, "check_task_anomaly")
                    , new CheckTaskAnomalyEntity(), checkTaskAnomalyNum1);
            if (checkTaskAnomalyNum1 > 0) {
                List<String> checkTaskAnomalyList = this.list(checkTaskAnomalySuperWrapper).stream().map(CheckTaskAnomalyEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(checkTaskAnomalyList);
                intersectionSuperList.add(checkTaskAnomalyList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object checkTaskAnomalyObj = authorizeService.getCondition(new AuthorizeConditionModel(checkTaskAnomalyQueryWrapper, checkTaskAnomalyPagination.getMenuId(), "check_task_anomaly"));
                if (ObjectUtil.isEmpty(checkTaskAnomalyObj)) {
                    return new ArrayList<>();
                } else {
                    checkTaskAnomalyQueryWrapper = (QueryWrapper<CheckTaskAnomalyEntity>) checkTaskAnomalyObj;
                    if (checkTaskAnomalyQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkTaskAnomalyNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object checkTaskAnomalyObj = authorizeService.getCondition(new AuthorizeConditionModel(checkTaskAnomalyQueryWrapper, checkTaskAnomalyPagination.getMenuId(), "check_task_anomaly"));
                if (ObjectUtil.isEmpty(checkTaskAnomalyObj)) {
                    return new ArrayList<>();
                } else {
                    checkTaskAnomalyQueryWrapper = (QueryWrapper<CheckTaskAnomalyEntity>) checkTaskAnomalyObj;
                    if (checkTaskAnomalyQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkTaskAnomalyNum++;
                    }
                }


            }
        }


        if (isPc) {
            if (ObjectUtil.isNotEmpty(checkTaskAnomalyPagination.getConfirmuserid())) {
                checkTaskAnomalyNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] confirmuserid = JsonUtil.getJsonToBean(checkTaskAnomalyPagination.getConfirmuserid(), String[][].class);
                    for (int i = 0; i < confirmuserid.length; i++) {
                        if (confirmuserid[i].length > 0) {
                            idList.add(confirmuserid[i][confirmuserid[i].length - 1]);
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> confirmuserid = JsonUtil.getJsonToList(checkTaskAnomalyPagination.getConfirmuserid(), String.class);
                        if (confirmuserid.size() > 0) {
                            idList.add(confirmuserid.get(confirmuserid.size() - 1));
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(checkTaskAnomalyPagination.getConfirmuserid()));
                    }
                }
                checkTaskAnomalyQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(CheckTaskAnomalyEntity::getConfirmuserid, tt).or();
                    });
                });

            }

            String parentid = checkTaskAnomalyPagination.getParentid();
            if (ObjectUtil.isNotEmpty(parentid)) {
                checkTaskAnomalyNum++;
                CheckTaskEntity info = checkTaskService.getOne(new LambdaQueryWrapper<CheckTaskEntity>().eq(CheckTaskEntity::getCode,parentid));
                if (info!=null){
                    parentid = info.getId();
                }
                checkTaskAnomalyQueryWrapper.lambda().like(CheckTaskAnomalyEntity::getParentid, parentid);

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            checkTaskAnomalyQueryWrapper.lambda().in(CheckTaskAnomalyEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            checkTaskAnomalyQueryWrapper.lambda().and(t -> t.in(CheckTaskAnomalyEntity::getId, finalAllSuperIDlist));
        }


        //排序
        if (StringUtil.isEmpty(checkTaskAnomalyPagination.getSidx())) {
            checkTaskAnomalyQueryWrapper.lambda().orderByDesc(CheckTaskAnomalyEntity::getId);
        } else {
            try {
                String sidx = checkTaskAnomalyPagination.getSidx();
                CheckTaskAnomalyEntity checkTaskAnomalyEntity = new CheckTaskAnomalyEntity();
                Field declaredField = checkTaskAnomalyEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                checkTaskAnomalyQueryWrapper = "asc".equals(checkTaskAnomalyPagination.getSort().toLowerCase()) ? checkTaskAnomalyQueryWrapper.orderByAsc(value) : checkTaskAnomalyQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        // 过滤条件

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<CheckTaskAnomalyEntity> page = new Page<>(checkTaskAnomalyPagination.getCurrentPage(), checkTaskAnomalyPagination.getPageSize());
                IPage<CheckTaskAnomalyEntity> userIPage = this.page(page, checkTaskAnomalyQueryWrapper);
                return checkTaskAnomalyPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<CheckTaskAnomalyEntity> list = new ArrayList();
                return checkTaskAnomalyPagination.setData(list, list.size());
            }
        } else {
            return this.list(checkTaskAnomalyQueryWrapper);
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos) {
                String field = info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_")) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if ("sub-jnpf".equals(type) && !field.contains("_jnpf_")) {
                    continue;
                }
                String fieldName = field;
                String table = "";
                if (field.contains("-")) {
                    fieldName = field.split("-")[1];
                }
                if (field.contains("_jnpf_")) {
                    fieldName = field.split("_jnpf_")[1];
                    table = field.split("_jnpf_")[0];
                    table = table.replace("jnpf_", "");
                }
                if ("sub-jnpf".equals(type) && !tableName.equals(table)) {
                    continue;
                }
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb = declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        } catch (Exception e) {
            return wrapper;
        }
    }

    @Override
    public CheckTaskAnomalyEntity getInfo(String id) {
        QueryWrapper<CheckTaskAnomalyEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CheckTaskAnomalyEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(CheckTaskAnomalyEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, CheckTaskAnomalyEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(CheckTaskAnomalyEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法


    //验证表单唯一字段
    @Override
    public String checkForm(CheckTaskAnomalyForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }

        return countRecover;
    }

    @Override
    public List<CheckTaskAnomalyEntity> listByDate(Date begin, Date end) {

        return this.list(
                new LambdaQueryWrapper<CheckTaskAnomalyEntity>()
        );
    }


}
